package com.ywt.cda.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * Created by Je on 2016/7/21.
 */
public class HeaderFilter implements Filter {
    private Pattern ignorePtn =null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String ignorePattern = filterConfig.getInitParameter("ignorePattern");
        if(ignorePattern!=null && ignorePattern.trim().length()>0){
            ignorePtn = Pattern.compile(ignorePattern.trim(),Pattern.CASE_INSENSITIVE);
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if(ignorePtn!=null){

            HttpServletRequest req = (HttpServletRequest) servletRequest;

            req.setAttribute("publicFlag",true);
            HttpServletResponse resp = (HttpServletResponse) servletResponse;
            resp.setHeader("Access-Control-Allow-Origin", "*");
            String path = req.getRequestURI().substring(
                    req.getContextPath().length());
            if (ignorePtn.matcher(path).find()) {
                servletRequest.getRequestDispatcher(path).forward(servletRequest, servletResponse);
            } else if (filterChain != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {

    }
}
